<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Requests;

use App\Models\InfoCategory;
use App\Models\InfoModel;
use App\Services\DictionaryService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

/**
 * 信息栏目分类表单验证
 * Class InfoCategoryRequest
 * @package App\Http\Requests
 */
class InfoCategoryRequest extends BaseRequest
{

    /**
     * 注入表单请求验证时自动校验
     *
     * @var bool
     */
    public $autoValidate = false;

    /**
     * 当前经过身份验证的用户是否可以执行请求操作
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 规则
     *
     * @return array
     */
    public function rules()
    {
        return [
            'id' => 'required|integer',
            'created_user_id' => 'required|integer',
            'type' => [
                'required',
                'integer',
                Rule::in(DictionaryService::getItemsValuesArray('infoCategoryTypeVar')),
            ],
            'info_model_id' => [
                'required_if:type,2',
                function ($attribute, $value, $fail) {
                    $info_model_ids = InfoModel::pluck('id')->toArray();
                    // 仅列表类型支持选择模型
                    if ($this->type == 2 && !in_array($value, $info_model_ids)) {
                        $fail(__('infoCategory.error_model'));
                    }
                }
            ],
            'parent_id' => [
                'nullable',
                'integer',
                function ($attribute, $value, $fail) {
                    $this->validateParent($value, $fail);
                }
            ],
            'name' => "required|min:2|max:50",
            'enname' => ['nullable', 'min:2', 'max:100', 'regex:/^[\sa-zA-Z]+$/', Rule::unique('info_category')->ignore($this->info_category)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'icon' => 'present',
            'cover_image' => [
                'nullable',
                function ($attribute, $value, $fail) {
                    AttachmentRequest::validity(__('infoCategory.cover_image'), $value, $fail, 1);
                }
            ],
            'keywords' => 'nullable|max:500',
            'description' => 'nullable|max:200',
            'href' => [
                'nullable',
                'required_if:type,4',
                'max:100'
            ],
            'href_target' => 'nullable|max:100',
            'rel' => 'nullable|max:20',
            'sort' => 'required|integer',
            'status' => 'required|boolean',
            'index_template' => 'nullable|max:20',
            'list_template' => 'nullable|max:20',
            'article_template' => 'nullable|max:20',
            'sort.*.id' => 'required|integer',
            'sort.*.sort' => 'required|integer',
        ];
    }

    /**
     * 定义场景
     * @var \string[][]
     */
    public $scenes = [
        'store' => [
            'created_user_id',
            'type',
            'info_model_id',
            'parent_id',
            'name',
            'enname',
            'icon',
            'cover_image',
            'keywords',
            'description',
            'href',
            'href_target',
            'rel',
//            'sort',
            'status',
            'index_template',
            'list_template',
            'article_template',
        ],
        'update' => [
            'parent_id',
            'name',
            'enname',
            'icon',
            'cover_image',
            'keywords',
            'description',
            'href',
            'href_target',
            'rel',
//            'sort',
            'status',
            'index_template',
            'list_template',
            'article_template',
        ],
        'destroy' => ['id'],
        'updateStatus' => ['status'],
        'updateSort' => ['sort.*.id', 'sort.*.sort']
    ];

    /**
     * 验证错误的自定义属性
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'id' => __('common.id'),
            'type' => __('infoCategory.type'),
            'info_model_id' => __('infoCategory.info_model_id'),
            'parent_id' => __('infoCategory.parent_id'),
            'name' => __('infoCategory.name'),
            'enname' => __('infoCategory.enname'),
            'icon' => __('infoCategory.icon'),
            'cover_image' => __('infoCategory.cover_image'),
            'keywords' => __('infoCategory.keywords'),
            'description' => __('infoCategory.description'),
            'index_template' => __('infoCategory.index_template'),
            'list_template' => __('infoCategory.list_template'),
            'article_template' => __('infoCategory.article_template'),
            'href' => __('common.href'),
            'href_target' => __('common.href_target'),
            'rel' => __('common.rel'),
            'status' => __('common.status'),
            'sort.*.id' => __('common.id'),
            'sort.*.sort' => __('common.sort'),
        ];
    }

    /**
     * 验证前
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->offsetSet('created_user_id', Auth::id());
        if (isset($this->keywords)) $this->offsetSet('keywords', join(',', $this->keywords));
        if (!isset($this->cover_image) || empty($this->cover_image)) $this->offsetSet('cover_image', 0);
        if (!isset($this->parent_id) || empty($this->parent_id)) $this->offsetSet('parent_id', 0);
        if (!isset($this->info_model_id) || empty($this->info_model_id)) $this->offsetSet('info_model_id', 0);
    }


    /**
     * 判断上一级栏目合法性
     * @param $value
     * @param $fail
     */
    public function validateParent($value, &$fail)
    {
        if (!empty($value)) {
            $parent = InfoCategory::find($value);
            if (!$parent) {
                $fail(__('infoCategory.parent_id') . __('common.http_not_found'));
            }

            if ($parent->type !== 1) {
                $fail(__('infoCategory.error_parent_id_is_not_channel'));
            }

            if (isset($this->id) && $this->id == $value) {
                $fail(__('infoCategory.error_pid_equal_id'));
            }
        }
    }


    /**
     * 提示信息
     *
     * @return array
     */
    public function messages()
    {
        return [
            'info_model_id.required_if' => __('infoCategory.error_empty_info_model_id'),
            'href.required_if' => __('infoCategory.error_empty_href')
        ];
    }


}


